{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6b96eaea-b4a4-4aa4-b380-bf6279db6fb6",
   "metadata": {},
   "source": [
    "Chapter 05\n",
    "\n",
    "# 城市街区距离\n",
    "Book_6《数据有道》 | 鸢尾花书：从加减乘除到机器学习"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c3be94fa-8ce0-4457-943f-9d7a063eafad",
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.spatial import distance\n",
    "from sklearn.metrics import pairwise_distances"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4503108c-f372-4297-9c18-96bff7ff3cbe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sample data points\n",
    "X = [[-5, 0], [4, 3], [3, -4]]\n",
    "\n",
    "# Query point\n",
    "q = [0, 0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "cd974726-3a43-4cfa-8da3-ee6da8c1eb3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compute the City Block (Manhattan) distance.\n",
    "d_1 = distance.cityblock(q, X[0])\n",
    "d_2 = distance.cityblock(q, X[1])\n",
    "d_3 = distance.cityblock(q, X[2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "efdb5540-ec65-494b-90e6-6b5bb839b67b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Pairwise City Block distances between X and q\n",
      "[[5.]\n",
      " [7.]\n",
      " [7.]]\n"
     ]
    }
   ],
   "source": [
    "# pairwise distances between rows of X and q\n",
    "dst_pairwise_X_q = pairwise_distances(X, [q], metric='cityblock')\n",
    "print('Pairwise City Block distances between X and q')\n",
    "print(dst_pairwise_X_q)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
